package com.codeoss.framework.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codeoss.framework.data.metadata.Table;
import com.codeoss.framework.data.store.ITableStore;
import com.codeoss.framework.response.ImageResponse;
import com.codeoss.framework.service.IImageService;
import com.codeoss.framework.util.IOUtil;
import com.codeoss.framework.util.Utils;

import java.util.Map;

@Service
public class ImageService implements IImageService {
	@Autowired
	private ITableStore tableStore;
	@Autowired
	private Utils utils;
	@Override
	public ImageResponse upload(MultipartFile file) {
		// TODO Auto-generated method stub
		ImageResponse imageResponse=new ImageResponse();
		String tempPath =System.getProperty("java.io.tmpdir")+File.separator;
		String filename=file.getOriginalFilename();
		String ext=filename.substring(filename.lastIndexOf(".")+1);
		String uuid=UUID.randomUUID().toString();
		String newFilename=uuid+"."+ext;
		imageResponse.setFilename(newFilename);
		File newFile=new File(tempPath+newFilename);
		FileOutputStream fos=null;
		try {
			fos=new FileOutputStream(newFile);
			fos.write(file.getBytes());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}finally {
			IOUtil.closeOutputStream(fos);
		}
		return imageResponse;
	}

	@Override
	public ImageResponse getImageByFilename(String filename) {
		// TODO Auto-generated method stub
		ImageResponse imageResponse=new ImageResponse();
		ByteArrayOutputStream os=new ByteArrayOutputStream();
		String tempPath =System.getProperty("java.io.tmpdir")+File.separator;
		File file=new File(tempPath+filename);
		FileInputStream fis=null;
		try {
			fis=new FileInputStream(file);
		    byte b[]=new byte[1024];
		    int len;
		    while((len=fis.read(b))!=-1){
		    	os.write(b, 0, len);
		    }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}finally {
			IOUtil.closeInputStream(fis);
		}
		imageResponse.setContent(os.toByteArray());
		return imageResponse;
	}
	
	@Override
	public ImageResponse getImageByField(Long id,String model,String dataField) {
		ImageResponse imageResponse=new ImageResponse();
		Table table = tableStore.get(model);
		BaseService baseService = utils.getBaseService(table);
		QueryWrapper query=new QueryWrapper();
		query.eq("id", id);
		query.select(dataField);
		Map<String,Object> map=baseService.getMap(query);
		if(map!=null) {
			byte b[]=(byte[])map.get(dataField);
			imageResponse.setContent(b);
		}
		return imageResponse;
	}
}
